package cn.edu.zjgsu.service.impl;

import cn.edu.zjgsu.dao.TopicinfoMapper;
import cn.edu.zjgsu.exception.WrongAuthorIdException;
import cn.edu.zjgsu.model.Topicinfo;
import cn.edu.zjgsu.model.TopicinfoExample;
import cn.edu.zjgsu.service.TopicService;
import cn.edu.zjgsu.templates.Page;
import cn.edu.zjgsu.templates.ResultBean;
import cn.edu.zjgsu.templates.ResultPageBean;
import cn.edu.zjgsu.util.CheckUtil;
import cn.edu.zjgsu.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TopicServiceImpl implements TopicService
{
    @Autowired
    private TopicinfoMapper topicinfoMapper;

    private TopicinfoExample topicinfoExample;

    private ResultPageBean resultPageBean;

    private ResultBean resultBean;

    @Override
    public Page<Topicinfo> getTopicsByPaging(Long authorId, Integer pageCount, Integer pageSize)
    {
        Page<Topicinfo> page = new Page<>();
        topicinfoExample = new TopicinfoExample();

        if (authorId == null)
        {
            throw new WrongAuthorIdException();
        }
        if (CheckUtil.checkPage(pageCount, pageSize))
        {
            topicinfoExample.setOffset(CommonUtil.getOffset(pageCount,pageSize));
            topicinfoExample.setLimit(pageSize);
            topicinfoExample.or().andAuthorIdEqualTo(authorId);
            page.setData(topicinfoMapper.selectByExample(topicinfoExample));
            page.setTotalCount(topicinfoMapper.countByExample(topicinfoExample));
            return page;
        }
        return null;
    }

    @Override
    public ResultBean<Integer> getTopicCount(Long authorId)
    {
        resultBean = new ResultBean<Integer>();
        topicinfoExample = new TopicinfoExample();

        if (authorId == null)
        {
            resultBean.noAuthorId();
            return  resultBean;
        }
        topicinfoExample.or().andAuthorIdEqualTo(authorId);
        resultBean.setData(topicinfoMapper.countByExample(topicinfoExample));
        return resultBean;
    }

    @Override
    public ResultBean<Integer> getTopicNumberOfPeople(List<Integer> rangeList)
    {
        resultBean = new ResultBean<Integer>();
        Integer min = rangeList.get(0);
        Integer max = rangeList.get(1);
        int resultCount;
        if(min!=null&&max!=null)
        {
            resultCount = topicinfoMapper.getCountOfNumberSeeTopic(min,max);
            resultBean.setData(resultCount);
            return resultBean;
        }else
        {
            resultBean.fail();
            return resultBean;
        }
    }
}
